package com.webserver.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Program: WebServerTomcat
 * @Author: Evan
 * @Date: 2022-05-16 17:44
 * @Description: 发送响应处理
 * @Version: V1.0
 */
public class HttpServletResponse {
    private int statusCode = 200;//状态代码
    private String statusReason = "OK";//状态描述
    /*响应头相关信息*/
    private Map<String, String> headers = new HashMap<>();
    /*响应正文信息*/
    private File entity;

    private Socket socket;

    public HttpServletResponse(Socket socket){
        this.socket = socket;
    }

    public void response() throws IOException {
        /*发送状态行*/
        sendStatusLine();
        /*发送响应头*/
        sendHeaders();
        /*发送正文*/
        sendContent();
    }

    /*发送状态行*/
    private void sendStatusLine() throws IOException {
        println("HTTP/1.1 "+statusCode+""+statusReason);
    }
    /*发送响应头*/
    private void sendHeaders() throws IOException {
        Set<Map.Entry<String, String>> entrySet = headers.entrySet();
        for (Map.Entry<String, String> e:entrySet) {
            String line = e.getKey()+": "+e.getValue();
            println(line);
        }
        println("");
    }
    /*发送响应正文*/
    private void sendContent() throws IOException {
        try(
            FileInputStream fis = new FileInputStream(entity);
                ) {
            OutputStream out = socket.getOutputStream();
            byte[] data = new byte[1024*10];
            int len;
            while ((len = fis.read(data)) != -1){
                out.write(data,0,len);
            }
        }
    }
    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);
        out.write(data);
        out.write(13);
        out.write(10);
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public File getEntity() {
        return entity;
    }

    public void setEntity(File entity) {
        this.entity = entity;
        try {
            addHeader("Content-Type", Files.probeContentType(entity.toPath()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        addHeader("Content-Length",entity.length()+"");
    }

    public void addHeader(String name,String value){
        this.headers.put(name,value);
    }
}
